package com.dmyang.p2pchat.activity;

import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dmyang.p2pchat.R;
import com.dmyang.p2pchat.bean.User;
import com.dmyang.p2pchat.comm.constant.GlobalConstant;
import com.dmyang.p2pchat.database.UserListDao;
import com.dmyang.p2pchat.service.NetListenService;
import com.dmyang.p2pchat.thread.RecieveDataThread;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {

    private static String IpAddress = "192.168.1.102";
    private static int Port = 8080;
    private EditText serverIp = null;
    private EditText serverPort = null;
    private EditText username = null;//昵称
    private Button regist = null;//昵称

    private String willSendStr = "init";
    private static RecieveDataThread recieveDataThread;

    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        //开启网络信息监听的后台服务
        /*Intent intent = new Intent(this, NetListenService.class);
        startService(intent);*/

        serverIp = (EditText) findViewById(R.id.et_server_ip);
        serverPort = (EditText) findViewById(R.id.et_port);
        username = (EditText) findViewById(R.id.et_username);
        regist = (Button) findViewById(R.id.bt_regist);

        serverPort.setText("10010");
        username.setText("侯亮平");
        serverIp.setText("192.168.1.103");


        //建立udp服务器线程，后台监听。
        if (recieveDataThread==null){
            //穿进去的本机ip好像没什么实质性的作用
            recieveDataThread = new RecieveDataThread(mContext,"192.168.1.102",9999);
            recieveDataThread.start();
        }


        regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int length = serverPort.getText().length();

                if (serverIp.getText().length()<1 || serverPort.getText().length()<1 || username.getText().length()<1){
                    Toast.makeText(getApplicationContext(), "请填写全部内容!", Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    //检查数据，尝试注册
                    //注册成功后，跳转到聊天页面

                    //获取wifi服务
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                    //判断wifi是否开启
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                    }
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    int ipAddress = wifiInfo.getIpAddress();
                    String ip = intToIp(ipAddress);//本机ip

                    //发送数据
                    willSendStr=ip+","+ "9999" +","+username.getText();
                    GlobalConstant.myNickName = username.getText().toString();
                    sendClass sendClass = new sendClass();
                    sendClass.start();



                    Intent intent = new Intent();
                    //(当前Activity，目标Activity)
                    intent.setClass(MainActivity.this, ListActivity.class);
                    startActivity(intent);

                }
            }
        });
    }
    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    /**
     * 发送数据的线程（网络通信）
     */
    public class sendClass extends Thread{
        @Override
        public void run() {
            DatagramSocket socket;
            try {
                //创建DatagramSocket对象并指定一个端口号，注意，如果客户端需要接收服务器的返回数据,
                //还需要使用这个端口号来receive，所以一定要记住
                int port = Integer.parseInt(serverPort.getText().toString());
                socket = new DatagramSocket(port);
                //使用InetAddress(Inet4Address).getByName把IP地址转换为网络地址
                //"192.168.1.105"
                InetAddress serverAddress = InetAddress.getByName(serverIp.getText().toString());
                String str = willSendStr;//设置要发送的报文
                byte data[] = str.getBytes();//把字符串str字符串转换为字节数组
                //创建一个DatagramPacket对象，用于发送数据。
                //参数一：要发送的数据  参数二：数据的长度  参数三：服务端的网络地址  参数四：服务器端端口号
                DatagramPacket packet = new DatagramPacket(data, data.length ,serverAddress ,port);
                socket.send(packet);//把数据发送到服务端。
                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
